//
//  MXFindVC.m
//  MXの衣柜
//
//  Created by 马霄 on 15/8/4.
//  Copyright (c) 2015年 霄 马. All rights reserved.
// 专题首页

#import "MXFindVC.h"
//---------------------- 添加Model类头文件 --------------------------------
#import "MXFindModel.h"
#import "MXFindTopView.h"
//---------------------- 添加三方头文件 --------------------------------
#import "SDCycleScrollView.h"
#import "AFNetworkHandler.h"
//---------------------- 添加自定义Cell --------------------------------
#import "MXFindContentCollectionViewCell.h"
//---------------------- 添加轮播图点击的WebView --------------------------------
#import "MXHomeWebViewVC.h"
//---------------------- 添加显示内容的VC --------------------------------
#import "MXFindDetailVC.h"

#import "MJRefresh.h"
#import "MXFindSearchVC.h"
#import "MBProgressHUD.h"
#define WIDTH ([UIScreen mainScreen].bounds.size.width)
#define HEIGHT ([UIScreen mainScreen].bounds.size.height)

@interface MXFindVC ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, SDCycleScrollViewDelegate, UISearchBarDelegate>
@property (nonatomic, retain) UICollectionView *collectionView;
//===========================轮播图属性部分===========================
@property (nonatomic, retain) MXFindTopView *topView;
@property (nonatomic, retain) NSMutableArray *urlStringArray;
//===========================轮播图属性部分===========================
@property (nonatomic, retain) NSMutableArray *ContentArray;


@property (nonatomic, retain) NSMutableArray *LunboLinkArray;

@property (nonatomic, assign) NSInteger pageNum;

@property (nonatomic, assign) NSInteger *contentSizeNum;

@property (nonatomic, retain) MBProgressHUD *HUD;

@property (nonatomic, retain) UIView *alterView;
/**
 * 创建searchBar
 */

@end

@implementation MXFindVC

- (void)dealloc
{
    [_HUD release];
    [_alterView release];
    [_topView release];
    [_ContentArray release];
    [_urlStringArray release];
    [_collectionView release];
    [super dealloc];
}

-(void)viewWillAppear:(BOOL)animated
{
    
    self.title = @"专题";
    
    self.navigationController.navigationBarHidden = NO;
    
    self.navigationController.navigationBar.translucent = NO;
    
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:26 / 255.0 green:62 / 255.0 blue:230 / 255.0 alpha:1];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"Home_titleBackGround"] forBarMetrics:UIBarMetricsDefault];

    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
// 设置searchBar
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemSearch) target:self action:@selector(rightButtonAction)];
    
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor blackColor];
    

    
    //创建集视图
    [self creatCollectionView];
    
    //引入数据
    [self GetFindData];
    
    
    
    
    
//    创建自定义的TopView 将三方的轮播图加在子视图上
    self.topView = [[[MXFindTopView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 120)] autorelease];
    
//    [self.topView.cycleScrollView addSubview:cycleScrollView];
    //轮播图的高度
    //网络加载 --- 创建带标题的图片轮播器
//    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, self.view.frame.size.width, topViewHeight) imageURLStringsGroup:nil]; // 模拟网络延时情景
    self.topView.cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    self.topView.cycleScrollView.delegate = self;
    self.topView.cycleScrollView.backgroundColor = [UIColor lightGrayColor];
    self.topView.cycleScrollView.placeholderImage = [UIImage imageNamed:@"plaseholder"];
    //标题的数组
    //    cycleScrollView.titlesGroup = self.TitleStringArray;
    //    cycleScrollView.dotColor = [UIColor blueColor]; // 自定义分页控件小圆标颜色
    //    cycleScrollView2.placeholderImage = [UIImage imageNamed:@"placeholder"];
    
    self.topView.cycleScrollView.dotColor = [UIColor clearColor];
    
//    [self.view addSubview:cycleScrollView];
    
    
    //             --- 模拟加载延迟
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //图片地址的数组
        self.topView.cycleScrollView.imageURLStringsGroup = self.urlStringArray;
        
    });

// 设置当前页
    self.pageNum = 1;
    
// 添加刷新方法
    [self loadingCollectionView];
    
    [self refreshTableView];
    // Do any additional setup after loading the view.
}
-(void)uiActivityindicatorviewStart
{
    self.alterView =[[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)] autorelease];
    self.alterView.backgroundColor =[UIColor whiteColor];
    self.HUD = [MBProgressHUD showHUDAddedTo:self.alterView animated:YES];
//    self.HUD.labelText = @"正在努力的给您加载";
    [self.HUD show:YES];
    
    [self.view addSubview:self.alterView];
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(uiActivityindicatorviewEnd) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

    
}
-(void)uiActivityindicatorviewEnd
{
    [self.alterView removeFromSuperview];
}
#pragma mark - FindTabBar设置CollectionView
- (void)creatCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[[UICollectionViewFlowLayout alloc] init] autorelease];
    flowLayout.itemSize = CGSizeMake(WIDTHPRO * 170, HEIGHTPRO * 210);
    flowLayout.minimumLineSpacing = 10;
    flowLayout.sectionInset = UIEdgeInsetsMake(WIDTHPRO * 10 ,HEIGHTPRO * 10 , 0,HEIGHTPRO * 10);
#pragma mark - 根据TopView手动更改
    flowLayout.headerReferenceSize = CGSizeMake(0, HEIGHTPRO  * 150);
    
    self.collectionView = [[[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) collectionViewLayout:flowLayout] autorelease];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionView];
    
    
    [self.collectionView registerClass:[MXFindContentCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    
    [self uiActivityindicatorviewStart];


}
#pragma mark -- 下拉刷新
-(void)refreshTableView
{
//    __block MXFindVC *findVC = self;
    [self.collectionView addHeaderWithCallback:^{
//        [self GetFindData];
        [self.collectionView headerEndRefreshing];
    }];
    //添加下拉刷新头部控件
  
//    [self.collectionView reloadData];
}

#pragma mark -- 上拉加载

-(void)loadingCollectionView
{
    
//    __unsafe_unretained typeof(self) vc = self;
    [self.collectionView addFooterWithCallback:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSString *urlStr = [NSString stringWithFormat:@"http://rm.app.hongniujia.com/json_rm.php?action=list&ver=10&page=%ld&category=nanren&category2=&pageSize=24&appCookie=channel_AppStore%%20version_6.11%%20oid_AE53CF37-EAEB-468C-8507-15A922FDD348%%20package_com.aslibra.rm.nanren%%20platform_iphone%%20ver_8.4%%20jb_0%%20t1_1438684307%20md5_62%%20t_1438671553&width=320&keyword=", (long)self.pageNum];
            self.pageNum += 1;
            [AFNetworkHandler GETwithAFNByURL:urlStr completion:^(id result) {
//                ----------------------------轮播部分----------------------------
                NSDictionary *topDict = [result objectForKey:@"top"];
                for (NSDictionary *dic in [topDict objectForKey:@"data"]) {
                    MXFindModel *topViewModel = [[[MXFindModel alloc] initWithDic:dic] autorelease];
                    [self.urlStringArray addObject:topViewModel.content];
                    
                    [self.LunboLinkArray addObject:topViewModel.link];
                }
                
                //----------------------------话题部分----------------------------
                
                NSArray *dataArr = [result objectForKey:@"data"];
                for (NSDictionary *dic in dataArr) {
                    
                    MXFindModel *model = [[MXFindModel alloc] initWithDic:dic];
                    
                    [self.ContentArray addObject:model];
                }
            }];
            [self.collectionView reloadData];
            [self.collectionView footerEndRefreshing];
        });
    }];
}

/*************************解析数据部分**************************/
- (void)GetFindData
{
    //全局数组初始化
    self.urlStringArray = [NSMutableArray array];
    self.ContentArray = [NSMutableArray array];
    self.LunboLinkArray = [NSMutableArray array];
    
    NSString *filepath = @"http://rm.app.hongniujia.com/json_rm.php?action=list&ver=10&page=0&category=nanren&category2=&pageSize=24&appCookie=channel_AppStore%20version_6.11%20oid_AE53CF37-EAEB-468C-8507-15A922FDD348%20package_com.aslibra.rm.nanren%20platform_iphone%20ver_8.4%20jb_0%20t1_1438684307%20md5_62%20t_1438671553&width=320&keyword=";
    [AFNetworkHandler GETwithAFNByURL:filepath completion:^(id result) {
//----------------------------轮播部分----------------------------
        NSDictionary *topDict = [result objectForKey:@"top"];
        for (NSDictionary *dic in [topDict objectForKey:@"data"]) {
            MXFindModel *topViewModel = [[[MXFindModel alloc] initWithDic:dic] autorelease];
            [self.urlStringArray addObject:topViewModel.content];
            
            [self.LunboLinkArray addObject:topViewModel.link];
        }
        
//----------------------------话题部分----------------------------

        NSArray *dataArr = [result objectForKey:@"data"];
        for (NSDictionary *dic in dataArr) {
            MXFindModel *model = [[MXFindModel alloc] initWithDic:dic];
            
            [self.ContentArray addObject:model];
          
        }
        
        [self.collectionView reloadData];
        [self.collectionView headerEndRefreshing];
        [self uiActivityindicatorviewEnd];
    }];
}
// 轮播图点击效果
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    MXHomeWebViewVC *webViewVC = [[MXHomeWebViewVC alloc]init];

    webViewVC.requestString = self.LunboLinkArray[index];
    if (index == 0) {
        webViewVC.titleSring = @"聚划算";
    } else if (index == 1) {
        webViewVC.titleSring = @"天猫男装";
    }
    [self presentViewController:webViewVC animated:YES completion:^{
        
    }];
    
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/************************* CollectionView Delegate **************************/

//Collection中的组别个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//每个组别中元件的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.ContentArray.count;
}

//重用机制
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MXFindContentCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
    cell.layer.masksToBounds = YES;
    [cell getInfo:self.ContentArray[indexPath.row]];
    return cell;
}

//collectionView 点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    MXFindDetailVC *detailVC = [[[MXFindDetailVC alloc] init] autorelease];
    MXFindModel *model = self.ContentArray[indexPath.row];
    detailVC.AlbumID = [self.ContentArray[indexPath.row] albumId];
    detailVC.TypeID = [self.ContentArray[indexPath.row] album_type];
    detailVC.TempImage = model.img;
    detailVC.TempTitleString = model.title;
    [self.navigationController pushViewController:detailVC animated:YES];
}

//设置HeaderView
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *topView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
    [topView addSubview:self.topView];
    return topView;
}



#pragma mark - 开始拖拽
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    self.tabBarController.tabBar.hidden = YES;
}
#pragma mark - 结束减速
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.tabBarController.tabBar.hidden = NO;
}

#pragma mark - 搜索按钮点击方法
- (void)rightButtonAction
{
    MXFindSearchVC *searcVC = [[[MXFindSearchVC alloc] init] autorelease];
    
    [self.navigationController pushViewController:searcVC animated:YES];
}


@end
